package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.CategoryMapper;
import com.itheima.Mapper.ProductMapper;
import com.itheima.Service.CategoryService;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public PageResult<Category> list(Category category) {
        // 设置分页参数
        PageHelper.startPage(category.getPage(), category.getPageSize());
        // 执行查询
        List<Category> productList = categoryMapper.list(category);
        // 解析分页结果
        Page<Category> page = (Page<Category>) productList;
        return new PageResult<Category>((int) page.getTotal(), productList);
    }

    @Override
    public Category getById(Integer id) {
        return categoryMapper.getById(id);
    }

    @Override
    @Transactional
    public void add(Category category) {
        // 若要在业务层设置创建时间，可在这里处理，也可依靠数据库默认值
//         category.setCreateTime(LocalDateTime.now());
//         category.setUpdateTime(LocalDateTime.now());
        categoryMapper.add(category);
    }

    @Override
    @Transactional
    public void update(Category category) {
        // 若要在业务层更新时间，可添加下面代码，或依靠数据库触发更新
        // category.setUpdateTime(LocalDateTime.now());

        categoryMapper.update(category);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        //先查询该分类下有无商品
        int i = productMapper.selectByfenleiId(Math.toIntExact(id));
        if (i>=1){
            throw new RuntimeException("该分类下有商品，请先删除商品");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public List<Category> fenleilist() {

         return categoryMapper.fenleilist();
    }
}